package at.fhooe.mc.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.system.Device;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.ui.component.Dialog;
import at.fhooe.mc.msports.Session;

public class XML {

	public static String WEB_URL = "http://84.23.78.113/bb/addsession.php";
	public static Random r= new Random();
	public static String createXML(Session s){	
		FileConnection fc = null;
		
		try{
			
			String fileUrl = "file:///SDCard/Databases/test.xml";
			fc = (FileConnection)Connector.open(fileUrl);
			
			if (fc.exists()) {
			      fc.delete();
			}

			fc.create();
			    
			OutputStream o = fc.openOutputStream();
			
			StringBuffer xml = new StringBuffer();
			xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
			xml.append("<session id = \""+r.nextLong()+"\">\n\t");
			
			for(int i = 0; i < s.getHeartRateTrace().size();i++){
				xml.append("<data>\n\t\t");
				
				int heartrate = Integer.parseInt(s.getHeartRateTrace().elementAt(i).toString());
				int steps = Integer.parseInt(s.getStepTrace().elementAt(i).toString());
				long timestamp = Long.parseLong(s.getTimeStamps().elementAt(i).toString());
				float calories = Float.parseFloat(s.getCalorieTrace().elementAt(i).toString());
				String str = s.getSpeedTrace().elementAt(i).toString();
				float speed;
				try{
					speed = Float.parseFloat(s.getSpeedTrace().elementAt(i).toString());
				}catch(Exception e){
					speed = 0.0f;
				}
				
				xml.append("<heartrate>" + heartrate + "</heartrate>\n\t\t");
				xml.append("<stepcount>"+ steps + "</stepcount>\n\t\t");
				xml.append("<timestamp>" + (timestamp/1000) + "</timestamp>\n\t\t");
				xml.append("<calories>" + calories + "</calories>\n\t");
				xml.append("<speed>"+speed+ "</speed>\n\t");
				
				if(i < s.getHeartRateTrace().size()-1)
					xml.append("</data>\n\t");
				else
					xml.append("</data>\n");
			}
			
			xml.append("</session>");
			
			o.write(xml.toString().getBytes());
			o.close();
			fc.close();
			
			return xml.toString();
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}finally{
			if(fc.isOpen()) {
				try {
					fc.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
		
	}
	
	public static boolean postXML(Session s){	
		try{
			String post = createXML(s);
			//Dialog.alert(post);
			if(post.compareTo("")!=0)
			{
				HttpConnection con = (HttpConnection)Connector.open(WEB_URL+";deviceside=true;interface=wifi");
				con.setRequestMethod(HttpConnection.POST);
				OutputStream o = con.openOutputStream();
				o.write(post.getBytes());
				int responseCode = con.getResponseCode();
				
				 InputStream is=con.openInputStream();
			     StringBuffer sb = new StringBuffer();
			              String xml = "";
			              int ch;

			              while((ch=is.read()) != -1){
			                  sb.append((char)ch);
			              }

			              xml = sb.toString();

			     Dialog.alert(xml);
				
				con.close();
				if(responseCode!=HttpConnection.HTTP_OK){
					return false;
				}else{
					return true;
				}
				
			}else{
				return false;
			}
		}
		catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}
